package com.xie.authority_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xie.authority_system.entity.Department;
import com.xie.authority_system.service.DepartmentService;
import com.xie.authority_system.dao.DepartmentMapper;
import com.xie.authority_system.utils.DepartmentTree;
import com.xie.authority_system.vo.query.DepartmentQueryVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
* @author XIEJINGCHENG
* @description 针对表【sys_department(部门表)】的数据库操作Service实现
* @createDate 2024-01-08 14:45:09
*/
@Service
@Transactional
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department>
    implements DepartmentService{


    @Override
    public List<Department> findDepartmentList(DepartmentQueryVo dept) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        // 部门名称
        queryWrapper.like(!ObjectUtils.isEmpty(dept.getDepartmentName()), "department_name", dept.getDepartmentName());
        // 排序
        queryWrapper.orderByAsc("order_num");
        // 查询部门列表
        List<Department> departmentList = baseMapper.selectList(queryWrapper);

        Optional<Department> max = departmentList.stream().min(new Comparator<Department>() {
            @Override
            public int compare(Department o1, Department o2) {
                return (int) (o1.getPid() - o2.getPid());
            }
        });

        Long pid = max.get().getPid();

        // 生成部门树
        List<Department> departmentTree = DepartmentTree.makeDepartmentTree(departmentList, pid);
        return departmentTree;
    }

    @Override
    public List<Department> findParentDepartment() {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();

        // 排序
        queryWrapper.orderByAsc("order_num");

        // 查询部门列表
        List<Department> departmentList = baseMapper.selectList(queryWrapper);

        // 创建部门对象
        Department department = new Department();
        department.setId(0L);
        department.setDepartmentName("顶级部门");
        department.setPid(-1L);
        department.setOrderNum(-1);
        departmentList.add(department);

        // 生成部门树
        List<Department> departmentTree = DepartmentTree.makeDepartmentTree(departmentList, -1L);

        return departmentTree;
    }
}




